package com.atguigu.gulimall.ware.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyRabbitConfig {

    /**
     * 使用JSON序列化机制，进行消息转换
     *
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 库存解锁逻辑
     * 交换机：stock-event-exchange
     * 队列1：stock.release.stock.queue，解锁库存服务需要监听该队列，该队列里的订单都是需要解锁库存的订单，通过路由键 stock.release.# 绑定交换机
     * 队列2：stock.delay.queue，延时队列，需要特殊配置，不允许任何人监听该队列，通过路由键 stock.locked 绑定交换机
     *
     * 具体流程：
     * 库存锁定成功后需要给队列2发送消息，队列2的消息过时后通过路由键 stock.release 将消息发送给交换机
     * 交换机再将消息发送给队列1，解锁库存服务监听队列1，判断订单是否创建完成以及是否取消等情况进行解锁库存。
     *
     */

    /**
     * 库存交换机
     *
     * @return
     */
    @Bean
    public Exchange stockEventExchange() {
        TopicExchange topicExchange = new TopicExchange("stock-event-exchange", true, false);
        return topicExchange;
    }

    /**
     * 库存释放队列
     *
     * @return
     */
    @Bean
    public Queue stockReleaseStockQueue() {
        Queue queue = new Queue("stock.release.stock.queue", true, false, false);
        return queue;
    }


    /**
     * 库存延时队列
     *
     * @return
     */
    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", "stock-event-exchange");
        arguments.put("x-dead-letter-routing-key", "stock.release");
        arguments.put("x-message-ttl", 120000); //单位毫秒,哭着大喊这里的120000一定不要写成字符串类型，因为这个搞了一上午
        Queue queue = new Queue("stock.delay.queue", true, false, false, arguments);
        return queue;
    }

    /**
     * 创建交换机与库存释放队列的绑定关系
     * @return
     */
    @Bean
    public Binding stockReleaseBinding(){
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",null);
    }

    /**
     * 创建交换机与库存延时队列的绑定关系
     * @return
     */
    @Bean
    public Binding stockLockedBinding(){
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",null);
    }
}
